package com.cloudcc.cloudframe.net.async;

import org.apache.http.Header;

import android.text.TextUtils;

import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.ServerStatusCode;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.cloudframe.util.NumberUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.loopj.android.http.TextHttpResponseHandler;

/** 
* @Description: 所有关于 json请求的基类
* @author wangzhiqiang
* @date 2015-11-24 下午1:55:57 
*  
*/
public abstract class JsonRequest extends TextHttpResponseHandler
		implements ServerStatusCode {

	private static final String NODE_RESULT ="result";
	private static final String NODE_RESULTCODE ="returnCode";
	private static final String NODE_RETURNINFO ="returnInfo";
	
	@Override
	public void onSuccess(int statusCode, Header[] headers,
			String responseString) {
		//如果 返回的null "" " " data数据参悟
		if (TextUtils.isEmpty(responseString)) {
			handleFailure(ErrorInfo.get(NET_DATA_EXCEPTION));
			return;
		}
		LogUtils.d("net", "网络请求数据" + responseString);
		
		//初始化json解析器
		JsonParser jsonParser = new JsonParser();
		//是否成功
		boolean result =false;
		//成功码
		int retrunCode =-1000;
		//失败提示 
		String returnInfo="";
		JsonObject rootJsonObject=null;
		try {
			//root对象
			rootJsonObject = jsonParser.parse(responseString).getAsJsonObject();
			//成功
			result = rootJsonObject.get(NODE_RESULT).getAsBoolean();
			retrunCode = NumberUtils.toInt(rootJsonObject.get(NODE_RESULTCODE)
					.getAsString(), -1000);
			returnInfo = rootJsonObject.get(NODE_RETURNINFO).getAsString();
		} catch (JsonSyntaxException e) {
			handleFailure(ErrorInfo.get(JSON_PARSER_ERROR));
			return;
		}catch(NullPointerException e){
			handleFailure(ErrorInfo.get(JSON_PARSER_ERROR));
			return;
		} catch(Exception e){
			handleFailure(ErrorInfo.get(JSON_PARSER_ERROR));
			return;
		}
		if (result && retrunCode == SUCCESS_OK) {
			handleSuccess(rootJsonObject, responseString);
		} else {
			handleFailure(ErrorInfo.get(retrunCode,returnInfo));
		}

	}

	@Override
	public void onFailure(int statusCode, Header[] headers,
			String responseString, Throwable throwable) {
		if (throwable != null && StringUtils.isNotBlank(throwable.getMessage())) {
			LogUtils.e("net", throwable.getMessage());
		}
		//处理检测问题
		if (statusCode==NET_INTERCEPTOR&&throwable!=null) {
			int errorCode = NumberUtils.toInt(throwable.getMessage(), -100);
			if (errorCode!=-100) {
				handleFailure(ErrorInfo.get(errorCode));
			}else{
				handleFailure(new ErrorInfo(NET_DATA_EXCEPTION));
			}
		}else{
			handleFailure(new ErrorInfo(NET_DATA_EXCEPTION));
		}
	}
	/**
	 * 处理 自定义json 
	 * @param resp
	 */
	public abstract void handleSuccess(JsonObject json, String resp);
	
	/**
	 * 处理 失败
	 * @param e
	 */
	public abstract void handleFailure(ErrorInfo e);
	


}
